/******************************************************************************
 * @File name   :      JobMgntServiceImpl.java
 *
 * @Author      :      cai junyi
 *
 * @Date        :      2011-10-25
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * 2011-10-25 上午9:55:26        cai junyi     1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.framework.common.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cap.bts.crmdp.dealer.masterinfo.service.DealerInfoDataSyncService;
import com.cap.bts.crmdp.dealer.masterinfo.service.WecareDataSyncService;
import com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService;
import com.cap.bts.crmdp.dealer.remind.scheduler.CustomerAndVehicleFileSynchronizationJob;
import com.cap.bts.crmdp.dealer.remind.scheduler.ServiceRemindFileSynchronizationJob;
import com.cap.bts.crmdp.dealer.remind.service.IRemindService;
import com.cap.bts.framework.common.constant.JobNameConstant;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.service.IJobMgntService;
import com.cap.bts.framework.common.util.ApplicationContextUtil;
import com.cap.bts.framework.common.util.CodeTextUtils;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.scheduler.constant.JobStatusType;
import com.cap.bts.framework.scheduler.constant.SchedulerErrorConstants;
import com.cap.bts.framework.scheduler.dao.IJobLoggerDao;
import com.cap.bts.framework.scheduler.dao.IJobServiceDao;
import com.cap.bts.framework.scheduler.domain.JobStatusLog;
import com.cap.bts.framework.scheduler.domain.SchedulerJob;
import com.cap.bts.framework.scheduler.dto.JobQueryDto;
import com.cap.bts.framework.scheduler.dto.JobResultDto;
import com.cap.bts.framework.scheduler.service.ISchedulerLoggerService;
import com.cap.bts.framework.sms.service.ISmContentService;
import com.cap.bts.framework.sms.util.HttpSMSProcessUtil;

/**
 *
 */
@Transactional(rollbackFor = AppException.class)
@Service
public class JobMgntServiceImpl implements IJobMgntService {
    
    @Autowired
    private IJobServiceDao jobServiceDao;
    
    @Autowired
    private ISchedulerLoggerService jobLoggerService;
    
    @Autowired
    private IJobLoggerDao jobLoggerDao;
    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2011-10-25
    **/
    @Override
    public List<JobResultDto> getJobByQueryDto(JobQueryDto queryDto) throws AppException {
        List<JobResultDto> results = new ArrayList<JobResultDto>();
        List<SchedulerJob> jobs = jobServiceDao.getJobsByQueryDto(queryDto);
        if(jobs != null && jobs.size() > 0){
            for(SchedulerJob job : jobs){
                JobResultDto result = new JobResultDto();
                result.setJobName(job.getJobName());
                result.setJobNum(job.getId());
//                Integer jobType = job.getJobType();
                String jobTypeValue = CodeTextUtils.getText("Job.cycle", job.getJobName());//job执行周期描述
                result.setJobTypeValue(jobTypeValue);
                
                
                JobStatusLog jobLog = jobLoggerDao.getLatestJobLogByName(job.getJobName());
                if(jobLog != null){
                    Integer jobStatus = jobLog.getJobStatus();
                    result.setJobStatus(jobStatus);
                    if(Utils.notNullAndZero(jobStatus)){
                        String jobStatusValue = CodeTextUtils.getText("Job.status", jobStatus);
                        result.setJobStatusValue(jobStatusValue);
                    }
                    result.setExeStartTime(jobLog.getJobStartTime());
                    result.setExeEndTime(jobLog.getJobEndTime());
                    result.setJobDesc(jobLog.getJobDesc());
                }

                results.add(result);
            }   
        }
        return results;
    }
    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2011-10-25
    **/
    @Override
    public boolean retryJob(String jobName) throws AppException { SchedulerJob job = jobServiceDao.getJobByName(jobName);
    if(job != null){
        
        long jobId = job.getId();
        int jobType = job.getJobType();
        int status = JobStatusType.SUCCESS.getValue();
        int retry = 0;
        Date startTime = new Date();
        String result = "job " + jobName + " run successfully.";
        Date endTime = new Date();
        try{
            
            if(JobNameConstant.PACKAGE_EXPIRATION_JOB.equals(jobName)){
                
                IMemberPackageService memberPackageService = (IMemberPackageService)ApplicationContextUtil.getBean("memberPackageServiceImpl");
                memberPackageService.processExpiredMemberPackageNew();
                System.out.println("retry job");
                
            }else if(JobNameConstant.PACKAGE_TOBE_ACTIVE_JOB.equals(jobName)){
                IMemberPackageService memberPackageService = (IMemberPackageService)ApplicationContextUtil.getBean("memberPackageServiceImpl");
                memberPackageService.processNotificationBeforeActivication();
                System.out.println("retry job");
                
            }else if(JobNameConstant.WECARE_DATA_SYNCHRONIZATION_JOB.equals(jobName)){
	        	WecareDataSyncService masterInfoService = (WecareDataSyncService) ApplicationContextUtil.getBean("wecareDataSyncService");
	    		masterInfoService.processSynchronizationDataFromWecare();
	        	
	        }else if(JobNameConstant.SERVICE_REMIND_FILE_SYNCHRONIZATION_JOB.equals(jobName)){
	    		ServiceRemindFileSynchronizationJob serJob = new ServiceRemindFileSynchronizationJob();
	    		serJob.work();
	        	System.out.println("retry job");
	        	
	        }else if(JobNameConstant.CUSTOMER_ANDVEHICLE_FILE_SYNCHRONIZATION_JOB.equals(jobName)){
	        	CustomerAndVehicleFileSynchronizationJob cusJob = new CustomerAndVehicleFileSynchronizationJob();
	        	cusJob.work();
	        	System.out.println("retry job");
	        	
	        }else if(JobNameConstant.Get_SMS_STATUTS_JOB.equals(jobName)){
	        	ISmContentService smContentService = (ISmContentService) ApplicationContextUtil
	    				.getBean("smContentService");
	    		//获取短信发送状态
	    		smContentService.batchInsertStatus(HttpSMSProcessUtil.loadStatus());
	        	
	        }else if(JobNameConstant.TENANT_SERVICE_CENTER_JOB.equals(jobName)){
	        	IRemindService remindService = (IRemindService) ApplicationContextUtil.getBean("remindServiceImpl");
	    		remindService.processTenantServiceCenterFile();
	        	System.out.println("retry job");
	        	
	        }else if(JobNameConstant.DEALER_INFO_UPADTE_JOB.equals(jobName)){
	        	DealerInfoDataSyncService dealerInfoDataSyncService = (DealerInfoDataSyncService) ApplicationContextUtil.getBean("dealerInfoDataSyncService");
	    		dealerInfoDataSyncService.processSynchronizationDataFromDealerInfo();
	        	System.out.println("retry job");
	        	
	        }
            /*else if(JobNameConstant.SEND_GET_TRIPINFO_JOB.equals(jobName)){
                ITripInfoService tripInfoService = (ITripInfoService)ApplicationContextUtil.getBean("tripInfoServiceImpl");
                tripInfoService.sendM3PRequest();

            
            }*/
            else {
                throw new AppException(SchedulerErrorConstants.JOB_NO_EXIST, "job name not found");
            }
        }catch(Exception e){
            e.printStackTrace();
            status = JobStatusType.RETRY_FAILED.getValue();
            result = "job " + jobName + " run with exception in retry " + retry + " . "
                + e.getMessage();
        }
        if(result.length() >= 500){
            result = result.substring(0, 490);
        }
        
        //log the result
        jobLoggerService
        .log(jobName, jobId, jobType, status, 0, startTime, endTime,result);
        
        } else {
        throw new AppException(SchedulerErrorConstants.JOB_NO_EXIST, "job not found");
        }
    
    return true;    
   }
    


}
